package rensoft.portfolio.client.view;

import static com.google.gwt.query.client.GQuery.$;
import static com.google.gwt.query.client.css.CSS.LEFT;
import static com.google.gwt.query.client.css.CSS.POSITION;

import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.query.client.css.Length;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FlowPanel;

import static cs.java.lang.Lang.doLater;

import cs.java.lang.Run;




import rensoft.gwt.client.Point;
import rensoft.gwt.client.view.View;
import rensoft.portfolio.client.lib.view.particles.ParticleEmiter;
import rensoft.portfolio.client.lib.view.particles.Scene;
import rensoft.portfolio.client.lib.view.particles.SceneImpl;
import rensoft.portfolio.client.lib.view.particles.Size;

public class ParticlesFontain extends View<FlowPanel> {
  private static final int WIDTH_OF_PORTFOLIO_WIDGET = 989;
  private Scene scene;

  public ParticlesFontain() {
    initWidget(new FlowPanel());
    if (Canvas.isSupported()) initialize();
  }

  private void centerSecene() {
    int widthForCentering =
        getWidth() < WIDTH_OF_PORTFOLIO_WIDGET ? WIDTH_OF_PORTFOLIO_WIDGET : getWidth();
    int sceneWidth = $(scene.asWidget()).width();
    if (widthForCentering > sceneWidth)
      setSceneLeft(-(sceneWidth - widthForCentering) / 2);
    else setSceneLeft((widthForCentering - sceneWidth) / 2);
  }

  private void initialize() {
    scene = new SceneImpl(new Size(1400, 900));
    scene.setRedrawColor("245,245,245,0.7");
    scene.add(new ParticleEmiter("large_particle_bluelight.png", new Point(-30, -0)));
    scene.add(new ParticleEmiter("large_particle_blue.png", new Point(30, -0)));
    scene.show();
    $(scene.asWidget()).css(POSITION.with(Position.RELATIVE));
    widget().add(scene);
    initializeCentering();
  }

  private void initializeCentering() {
    doLater(new Run() {
      public void run() {
        centerSecene();
      }
    });
    Window.addResizeHandler(new ResizeHandler() {
      public void onResize(ResizeEvent event) {
        centerSecene();
      }
    });
  }

  private void setSceneLeft(int left) {
    $(scene.asWidget()).css(LEFT.with(Length.px(left)));
  }
}
